#include "threadPool.h"
#include "head.h"

int makeWorker(threadPool_t *threadPool){
    for(int i = 0; i < threadPool->workerNum; ++i){
        pthread_create(&threadPool->tidArr[i],NULL,threadFunc,threadPool);
    }
    return 0;
}

void *threadFunc(void *arg){
    threadPool_t *threadPool = (threadPool_t *)arg;

    while(1){
        // 取出任务
        pthread_mutex_lock(&threadPool->taskQueue.mutex);
        while(threadPool->exitflag == 0 && threadPool->taskQueue.queueSize == 0){
            pthread_cond_wait(&threadPool->taskQueue.cond, &threadPool->taskQueue.mutex);
        }
        if(threadPool->exitflag != 0){
            printf("child is going to exit!\n");
            pthread_mutex_unlock(&threadPool->taskQueue.mutex);
            pthread_exit(NULL);
        }
        printf("child get a task!\n");
        int netfd = threadPool->taskQueue.pFront->netfd;
        deQueue(&threadPool->taskQueue);
        pthread_mutex_unlock(&threadPool->taskQueue.mutex);
        // 执行任务
        char username[256] = {0};
        char mkdirPath[256] = {0};
        int length;
        recv(netfd,&length,sizeof(int),MSG_WAITALL);
        recv(netfd,username,length,MSG_WAITALL);
        int ret = mkdir(username,0777);
        perror("mkdir1");
        sprintf(mkdirPath,"%s/%s",username,"netdisk");
        ret = mkdir(mkdirPath,0777);
        perror("mkdir2");
        if(ret == 0)
        {
            train_t train;
            train.length = strlen(mkdirPath);
            strcpy(train.data,mkdirPath);
            send(netfd,&train,sizeof(int)+train.length,MSG_NOSIGNAL);
        }         

        int orderflag;
        char path[256] = {0};
        recvOrder(netfd,&orderflag,path);

        close(netfd);
        // 恢复空闲
        printf("child finish a task!\n");
    }
}

